package com.imooc.product.controller;

import com.imooc.product.VO.ProductInfoVO;
import com.imooc.product.VO.ProductVO;
import com.imooc.product.VO.ResultVO;
import com.imooc.product.dataobject.ProductCategory;
import com.imooc.product.dataobject.ProductInfo;
import com.imooc.product.service.impl.ProductCategoryServiceImpl;
import com.imooc.product.service.impl.ProductInfoServiceImpl;
import com.imooc.product.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductCategoryServiceImpl productCategoryService;

    @Autowired
    private ProductInfoServiceImpl productInfoService;

    @GetMapping("/list")
    public ResultVO list() {
        //查询所有上架商品
        List<ProductInfo> productInfoList = productInfoService.findUpAll();
        //获取所有商品的
        List<Integer> categoryTypeList = new ArrayList<>();
        HashSet<Integer> categoryTypeSet = new HashSet<>();
        for (ProductInfo productInfo : productInfoList) {
            //categoryTypeList.add(productInfo.getCategoryType());
            categoryTypeSet.add(productInfo.getCategoryType());
        }

        for(Integer type : categoryTypeSet) {
            categoryTypeList.add(type);
        }
        //查询所有商品类目
        List<ProductCategory> productCategoryList = productCategoryService.findByCategoryTypeIn(categoryTypeList);

        //首页商品列表vo
        List<ProductVO> productVOList = new ArrayList<>();

        if (!CollectionUtils.isEmpty(productCategoryList) && !CollectionUtils.isEmpty(productInfoList)) {
            for (ProductCategory productCategory : productCategoryList) {
                ProductVO productVO = new ProductVO();
                productVO.setCategoryName(productCategory.getCategoryName());
                productVO.setCategoryType(productCategory.getCategoryType());
                //商品详情列表vo
                List<ProductInfoVO> productInfoVOList = new ArrayList<>();

                for (ProductInfo productInfo : productInfoList) {
                    if (productCategory.getCategoryType().equals(productInfo.getCategoryType())) {
                        ProductInfoVO productInfoVO = new ProductInfoVO();
                        BeanUtils.copyProperties(productInfo, productInfoVO);
                        productInfoVOList.add(productInfoVO);
                    }
                }
                productVO.setProductInfoVOList(productInfoVOList);
                productVOList.add(productVO);
            }
        }

        return ResultVOUtil.success(productVOList);
    }
}
